package com.yipinhouse.signing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.yipinhouse.common.exception.HouseException;
import com.yipinhouse.signing.common.SigningResultCode;
import com.yipinhouse.signing.common.util.OssUtil;
import com.yipinhouse.signing.infra.model.Contract;
import com.yipinhouse.signing.infra.model.ContractAttachment;
import com.yipinhouse.signing.infra.mapper.ContractAttachmentMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipinhouse.signing.service.ContractAttachmentService;
import com.yipinhouse.signing.service.ContractService;
import com.yipinhouse.signing.service.param.ContractAttachmentModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WangCong
 * @since 2022-12-02
 */
@Service
public class ContractAttachmentServiceImpl extends ServiceImpl<ContractAttachmentMapper, ContractAttachment> implements ContractAttachmentService {
    @Resource
    private ContractService contractService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadContractAttachment(List<ContractAttachmentModel> fileList, Integer contractId) throws Exception {

//        上传所有文件
        for (ContractAttachmentModel file : fileList) {
            String path = OssUtil.uploadFile("yipinhouse", file.getFileName(), file.getInputStream());
            file.setFilePath(path);
        }
//        判断合同是否存在
        //TODO 合同状态是否应该存在
        Contract contract = contractService.getById(contractId);
        if (contract==null)
            throw new HouseException(SigningResultCode.CONTRACT_NOT_EXISTS);

//        上传合同附件至数据库
        List<ContractAttachment> attachments = new ArrayList<>();

        for (ContractAttachmentModel model : fileList) {
            ContractAttachment attachment = BeanUtil.toBean(model, ContractAttachment.class);
            attachment.setContractId(contractId);
            attachment.setCreateDate(DateUtil.now());
            attachment.setStatus(1);
            attachments.add(attachment);
        }
        this.saveBatch(attachments);
    }
}
